<style lang="scss">
@import "@/assets/css/variable";
.applyForm {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: $main-bgc;
  min-height: 100%;
  overflow: auto;
  box-sizing: border-box;
  padding: 1.6rem;
  .box1 {
    background-color: white;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    .line {
      font-size: 1.2rem;
      display: flex;
      align-items: center;
      span {
        flex: 1;
      }
    }
  }
  .box2 {
    background-color: white;
    .line {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
    }
    .title {
      font-size: 1.4rem;
      font-weight: bold;
    }
  }
}
</style>
<template>
  <div class="applyForm">
    <div class="box1 padding-all-m border-r-l" v-if="item">
      <div class="title title-l">{{ item.title }}</div>
      <div class="line margT-l">
        <span class="label color-s">原价</span
        ><span class="value">{{ val.price }}元</span>
      </div>
      <div class="line margT-l">
        <span class="label color-s">发货方式</span
        ><span class="value">{{
          item.val.commodity_type == 1 ? "自提" : "发货"
        }}</span>
      </div>
      <div
        v-if="offeredItem.group_ids || offeredItem.group_id || group_id"
        class="line margT-l"
      >
        <span class="label color-s">拼团价</span
        ><span class="value" :style="{ color: theme_color }">{{
          val.chief_price + "元"
        }}</span>
      </div>
      <div v-else class="line margT-l">
        <span class="label color-s">团长价</span
        ><span class="value" :style="{ color: theme_color }">{{
          val.team_price + "元"
        }}</span>
      </div>
      <div class="line margT-l">
        <span class="label color-s">商户电话</span>
        <span class="value pheone" style="display: flex; align-items: center"
          >{{ merchant.mobile }}
          <a :href="'tel:' + item.mobile" style="margin-left: 10px">
            <van-icon name="phone" size="1.5rem" :color="theme_color" />
          </a>
        </span>
      </div>
      <div class="line margT-l">
        <span class="label color-s">商户地址</span>
        <span class="value pheone" style="display: flex; align-items: center"
          >{{ address }}
          <van-icon
            name="location"
            size="1.5rem"
            :color="theme_color"
            @click="mapClick(address)"
          />
        </span>
      </div>
    </div>
    <div class="box2 padding-all-m border-r-l margT-l" v-if="item">
      <div>
        <span class="title">请填写详细地址</span
        ><span class="color-s fs-12 margL-l"
          >以下均为<span :style="{ color: theme_color }">必填</span></span
        >
      </div>
      <div>
        <div class="margT-l" v-if="item.create_form">
          <k-form-build
            :dynamicData="orderItem.val[0]"
            v-if="orderItem.statusname == '未支付'"
            ref="kfb"
            :value="item.create_form"
          />
          <k-form-build v-else ref="kfb" :value="item.create_form" />
        </div>
      </div>
    </div>
    <div class="fix-bottom padding-lr">
      <van-button :color="theme_color" block @click="submit">提交</van-button>
    </div>
    <!-- <div style="">openId:{{openid}}</div> -->
    <!-- <div>openId2:{{openId2}}</div> -->
  </div>
</template>

<script>
import { Button, Toast, Dialog, Icon } from "vant";
// import Vue from 'vue'
import KFormDesign from "k-form-design";
// import 'k-form-design/lib/k-form-design.css';
Vue.use(KFormDesign);
// import utils from '@/assets/js/utils.js';

export default {
  name: "ApplyForm",
  components: {
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    [Icon.name]: Icon,
    KFormDesign,
  },
  data() {
    return {
      item: "",
      openid: "",
      val: "",
      offeredItem: {},
      orderItem: {},
      tuistatus: 2,
      group_id: null,
      p_openid: "",
      falg: true,
      activity_id: null,
      theme_color: "",
      staff_id: null,
      merchant: {},
    };
  },
  // computed: {
  //     getOpenId() {
  //         this.openid = this.$store.state.openid
  //         return this.openid
  //     }
  // },
  mounted() {
    this.offeredItem = this.$store.state.offeredItem;
    console.log(this.offeredItem, this.$store.state);
    this.item = this.$store.getters.getActivityItem;
    this.merchant = this.$store.state.merchant;
    this.address = this.merchant.province + this.merchant.city+this.merchant.area+this.merchant.detail_address
    this.activity_id = this.$route.query.activity_id;
    this.orderItem = this.$store.state.orderItem;
    this.theme_color = this.$store.state.theme_color;
    this.staff_id = this.$route.query.staff_id;
    this.val = this.item.val;
    this.group_id = this.$store.state.group_id;
    this.p_openid = this.$store.state.p_openid;
    // console.log(item);
    if (!this.item) {
      this.$router.go(-1);
    }
    if ((this.tuistatus = 2 && !this.item)) {
      this.$router.go(-2);
    }
    this.openid = localStorage.getItem("COPENID");
  },
  methods: {
    mapClick(adress) {
      this.shareInit();
      this.getLal(adress, (res) => {
        this.openLocation(
          res.detail.addressComponents.street,
          res.detail.location.lat,
          res.detail.location.lng
        );
      });
    },
    shareInit() {
      const _this = this;
      const url = location.href.split("#")[0];
      let params = {
        url: url,
      };
      _this.$request.configJssdk(params).then((res) => {
        console.log(res, "-------------res");
        wx.config({
          debug: false, // 是否开启调试模式
          appId: res.data.appId, //appid
          timestamp: res.data.timestamp, // 时间戳
          nonceStr: res.data.nonceStr, // 随机字符串
          signature: res.data.signature, // 签名
          jsApiList: ["openLocation", "getLocation"], // 需要使用的JS接口列表
        });
      });
    },
    getLal(address, cb) {
      var geocoder = new qq.maps.Geocoder();
      geocoder.getLocation(address);
      geocoder.setComplete(function (res) {
        cb(res);
      });
      geocoder.setError(function (err) {
        cb(res);
      });
    },

    openLocation(name, lat, lng) {
      wx.openLocation({
        latitude: lat,
        longitude: lng,
        name: name,
        address: this.address,
        scale: 14,
        infoUrl: "http://weixin.qq.com",
      });
    },
    submit() {
      const _this = this;
      _this.$refs.kfb
        .getData()
        .then((values) => {
          // console.log('验证通过', values)
          // values.create_time = utils.formatDateYMDHM(new Date())
          // values.openid = _this.openid
          // values.is_sure = 0
          let apply_list = [];
          // values.toString()
          apply_list.push(values);

          //values.name = utils.formatName(values.name)
          // console.log("_this.item.apply_list",_this.item.apply_list)
          // let apply_list = []
          // console.log("typeof _this.item.apply_list == object", typeof _this.item.apply_list == 'object' )
          // if(typeof _this.item.apply_list == 'Array' || typeof _this.item.apply_list == 'object') {
          //     // apply_list = []
          //     apply_list = _this.item.apply_list==null?[]:_this.item.apply_list
          //     console.log("======values======",values)
          //     console.log("======apply_list======",apply_list)
          //     apply_list.push(values)
          // }else{
          //     apply_list = []
          //     apply_list.push(values)
          // }
          // _this.activitySave(apply_list)
          _this.getOrderSave(apply_list);
        })
        .catch(() => {
          console.log("验证未通过，获取失败");
        });
    },
    getOrderSave(apply_list) {
      const _this = this;
      if (_this.falg) {
        // 参团
        _this.falg = false;
        // console.log(_this.offeredItem, 3333333333333);
        if (_this.group_id && _this.p_openid) {
          let params = {
            activity_id: _this.activity_id, // 活动ID
            val: JSON.stringify(apply_list), // 自定义表单数据
            // status: 1,// 是否打款 1否 2是
            // writeoff: 1,// 是否核销 1否 2是
            // ordersn: '',// 订单编号
            // paytime: '',// 支付时间
            // transid: '',// 微信订单号
            price: _this.val.chief_price, // 单价
            num: 1, // 数量
            p_openid: _this.p_openid,
            openid: _this.openid,
            group_id: _this.group_id,
            staff_id: _this.staff_id,
            // id: _this.item.id,// 修改的时候需要传
            // apply_list: apply_list
          };
          //   alert('getOrderSave_params:' + JSON.stringify(params))
          // console.log(params, 'paramsparamsparamsparamsparams');
          this.$request
            .getInvitation(params)
            .then((res) => {
              //   alert('res'+JSON.stringify(res))
              if (res.ret == 400) {
                Dialog({ message: res.msg });
                return;
              } else if (res.data == 2) {
                Toast("团已满,无法参团");
                return;
              } else if (res.ret == 200) {
                let group_id = res.data.group_id;
                let order_id = res.data.order_id;
                // console.log(group_id, 'group_id');
                let weixinParams = {
                  appId: res.data.appId, // 公众号appId，由商户传入
                  nonceStr: res.data.nonceStr, // 随机串
                  package: res.data.package,
                  paySign: res.data.paySign, // 微信签名
                  signType: res.data.signType, // 微信签名方式
                  timeStamp: res.data.timeStamp, // 时间戳
                };
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  weixinParams,
                  function (res) {
                    // Toast(res.err_msg)
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                      _this.falg = true;
                      Toast("支付成功!");
                      setTimeout(function () {
                        Toast("参团成功");
                        _this.$router.push(
                          `/caseShow/groupBuying/GroupDetails/${group_id}?order_id=${order_id}&activity_id=${_this.activity_id}`
                        );
                      }, 1000);
                      // WeixinJSBridge.call('closeWindow');
                    } else if (
                      res.err_msg == "get_brand_wcpay_request:cancel"
                    ) {
                      Toast("取消支付!");
                      _this.falg = true;
                      _this.$router.go(-1);
                      // WeixinJSBridge.call('closeWindow');
                    } else {
                      Toast("支付失败!");
                      _this.falg = true;
                      _this.$router.go(-1);
                    }
                    // _this.$router.go(-1)
                    // WeixinJSBridge.call('closeWindow');
                  }
                );
              }
            })
            .catch((res) => {
              Toast("出错了");
            });
        } else if (_this.offeredItem.group_id) {
          let params = {
            activity_id: _this.activity_id, // 活动ID
            val: JSON.stringify(apply_list), // 自定义表单数据
            // status: 1,// 是否打款 1否 2是
            // writeoff: 1,// 是否核销 1否 2是
            // ordersn: '',// 订单编号
            // paytime: '',// 支付时间
            // transid: '',// 微信订单号
            price: _this.val.chief_price, // 单价
            num: 1, // 数量
            openid: _this.openid,
            group_id: _this.offeredItem.group_id,
            staff_id: _this.staff_id,
            // id: _this.item.id,// 修改的时候需要传
            // apply_list: apply_list
          };
          // console.log(params, 'paramsparamsparamsparamsparams');
          this.$request
            .getSavaMam(params)
            .then((res) => {
              if (res.ret == 400) {
                Dialog({ message: res.msg });
                return;
              } else if (res.data == 1) {
                Toast("拼团时间结束,无法继续参团");
                return;
              } else if (res.data == 2) {
                Toast("团已满,无法参团");
                return;
              } else if (res.data == 3) {
                Toast("您已参加过此团,无法继续参加");
                return;
              } else if (res.ret == 200) {
                let group_id = res.data.group_id;
                let order_id = res.data.order_id;
                // console.log(group_id, 'group_id');
                let weixinParams = {
                  appId: res.data.appId, // 公众号appId，由商户传入
                  nonceStr: res.data.nonceStr, // 随机串
                  package: res.data.package,
                  paySign: res.data.paySign, // 微信签名
                  signType: res.data.signType, // 微信签名方式
                  timeStamp: res.data.timeStamp, // 时间戳
                };
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  weixinParams,
                  function (res) {
                    // Toast(res.err_msg)
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                      _this.falg = true;
                      Toast("支付成功!");
                      setTimeout(function () {
                        Toast("参团成功");
                        _this.$router.push(
                          `/caseShow/groupBuying/GroupDetails/${group_id}?order_id=${order_id}&activity_id=${_this.activity_id}`
                        );
                      }, 1000);
                      // WeixinJSBridge.call('closeWindow');
                    } else if (
                      res.err_msg == "get_brand_wcpay_request:cancel"
                    ) {
                      _this.falg = true;
                      Toast("取消支付!");
                      _this.$router.go(-1);
                      // WeixinJSBridge.call('closeWindow');
                    } else {
                      _this.falg = true;
                      Toast("支付失败!");
                      _this.$router.go(-1);
                    }
                    // _this.$router.go(-1)
                    // WeixinJSBridge.call('closeWindow');
                  }
                );
              }
            })
            .catch((res) => {
              Toast("出错了");
            });
        } else {
          // 开团
          let params = {
            activity_id: _this.activity_id, // 活动ID
            val: JSON.stringify(apply_list), // 自定义表单数据
            // status: 1,// 是否打款 1否 2是
            // writeoff: 1,// 是否核销 1否 2是
            // ordersn: '',// 订单编号
            // paytime: '',// 支付时间
            // transid: '',// 微信订单号
            price: _this.val.chief_price, // 单价
            num: 1, // 数量
            openid: _this.openid,
            staff_id: _this.staff_id,
            // id: _this.item.id,// 修改的时候需要传
            // apply_list: apply_list
          };
          this.$request
            .getSavaOrder(params)
            .then((res) => {
              if (res.ret == 400) {
                Dialog({ message: res.msg });
                return;
              } else if (res.ret == 200) {
                let group_id = res.data.group_id;
                let order_id = res.data.order_id;
                let weixinParams = {
                  appId: res.data.appId, // 公众号appId，由商户传入
                  timeStamp: res.data.timeStamp, // 时间戳
                  nonceStr: res.data.nonceStr, // 随机串
                  package: res.data.package,
                  signType: res.data.signType, // 微信签名方式
                  paySign: res.data.paySign, // 微信签名
                };
                WeixinJSBridge.invoke(
                  "getBrandWCPayRequest",
                  weixinParams,
                  function (res) {
                    // Toast(res.err_msg)
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                      _this.falg = true;
                      Toast("支付成功!");
                      setTimeout(function () {
                        Toast("拼团成功");
                        _this.$router.push(
                          `/caseShow/groupBuying/GroupDetails/${group_id}?order_id=${order_id}&activity_id=${_this.activity_id}`
                        );
                      }, 1000);
                      // WeixinJSBridge.call('closeWindow');
                    } else if (
                      res.err_msg == "get_brand_wcpay_request:cancel"
                    ) {
                      _this.falg = true;
                      Toast("取消支付!");
                      _this.$router.go(-1);
                      // WeixinJSBridge.call('closeWindow');
                    } else {
                      _this.falg = true;
                      Toast("支付失败!");
                      _this.$router.go(-1);
                    }
                    // _this.$router.go(-1)
                    // WeixinJSBridge.call('closeWindow');
                  }
                );
              }
            })
            .catch((res) => {
              Toast("出错了");
            });
        }
      }
    },
    activitySave(apply_list) {
      const _this = this;
      let params = {
        openid: _this.openid,
        id: _this.item.id,
        apply_list: apply_list,
      };
      // console.log("params",params)
      this.$request
        .activitySave(params)
        .then((res) => {
          if (res.ret == 200) {
            Toast("操作成功");
            setTimeout(function () {
              // _this.$router.go(-1)
              _this.$router.push("/caseShow/groupBuying/GroupDetails");
            }, 2000);
          }
        })
        .catch((res) => {
          Toast("出错了");
        });
    },
  },
};
</script>